package org.devocean.groupbuying.web.frontend;

import java.util.Map;

import javax.validation.Valid;

import org.devocean.groupbuying.domain.Contact;
import org.devocean.groupbuying.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = { "/{lang:[a-z]{2}}" })
// @RequestMapping(value={"", "/{lang:[a-z]{2}}"})
public class ContactController {

	@Autowired
	private ContactService contactService;


	@RequestMapping("/")
	public String index(Map<String, Object> map) {

		map.put("contactList", contactService.getAllContacts());

		return "contact/list";
	}

	@RequestMapping("/index")
	public String listContacts(Map<String, Object> map) {

		map.put("contact", new Contact());
		map.put("contactList", contactService.getAllContacts());

		return "contact/list";
	}

	@RequestMapping(value = "/contact/add", method = RequestMethod.POST)
	public String addContact(@Valid Contact contact, BindingResult result,
			Map<String, Object> map) {
		if (!result.hasErrors()) {
			if (contact.getId() != null)
				contactService.updateContact(contact);
			else
				contactService.add(contact);
			map.put("contact", contact);

		}
		return "contact/add";
	}

	@RequestMapping("/contact")
	public String createForm(Model uiModel) {
		uiModel.addAttribute(new Contact());
		return "contact/add";
	}

	@RequestMapping(value = "/contact/{id}", produces = "text/html")
	public String updateForm(@PathVariable("id") Integer id, Model uiModel) {
		uiModel.addAttribute(contactService.getContact(id));
		return "contact/add";
	}

	@RequestMapping("/edit/{permalink:[a-z_]+}-{contactId:\\d+}")
	public String editContact(@PathVariable("contactId") Integer contactId,
			Map<String, Object> map) {
		Contact contact = contactService.getContact(contactId);
		map.put("contact", contact);
		return "contact/edit";
	}

	@RequestMapping("/delete/{contactId}")
	public String deleteContact(@PathVariable("contactId") Integer contactId) {

		contactService.removeContact(contactId);

		return "redirect:/index";
	}
}
